<template>
  <div ref="imgWrap" class="wrap" @mousewheel.prevent="rollImg">
    <img
      :src="url"
      alt
      ref="image"
      @mousedown.prevent="moveImg"
      style="width: 100%; height: 100%"
    />
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      url: 'https://w.wallhaven.cc/full/8o/wallhaven-8oky1j.jpg',
    };
  },
  computed: {},
  watch: {},
  created() {},
  async mounted() {},
  methods: {
    rollImg(e) {
      let transform = this.$refs.image.style.transform;
      let zoom = transform.indexOf('scale') != -1 ? +transform.split('(')[1].split(')')[0] : 1;
      zoom += e.wheelDelta / 1200;
      if (zoom > 0.1 && zoom < 2) {
        this.$refs.image.style.transform = 'scale(' + zoom + ')';
      }
    },

    moveImg(e) {
      let wrap = this.$refs.imgWrap;
      let img = this.$refs.image;
      let x = e.pageX - img.offsetLeft;
      let y = e.pageY - img.offsetTop;
      // 添加鼠标移动事件
      wrap.addEventListener('mousemove', move);
      function move(e) {
        img.style.left = e.pageX - x + 'px';
        img.style.top = e.pageY - y + 'px';
      }
      // 添加鼠标抬起事件，鼠标抬起，将事件移除
      img.addEventListener('mouseup', () => {
        wrap.removeEventListener('mousemove', move);
      });
      // 鼠标离开父级元素，把事件移除
      wrap.addEventListener('mouseout', () => {
        wrap.removeEventListener('mousemove', move);
      });
    },
  },
};
</script>

<style scoped>
.wrap {
  position: relative;
  width: 400px;
  height: 300px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}
img {
  position: absolute;
  cursor: move;
  max-width: 100%;
  max-height: 100%;
  display: block;
  margin: auto;
}
</style>
